package asia.njut.reader.activity;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.geometerplus.android.fbreader.FBReaderApplication;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import asia.njut.reader.R;
import asia.njut.reader.R.id;
import asia.njut.reader.R.layout;
import asia.njut.reader.R.menu;
import asia.njut.reader.R.string;
import asia.njut.reader.utils.Commons;
import asia.njut.reader.utils.ToolUtils;
import asia.njut.reader.view.CustomDialog;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity {
	/**
	 * A dummy authentication store containing known user names and passwords.
	 * TODO: remove after connecting to a real authentication system.
	 */
	
	private RelativeLayout aboutDialoglayout;

	private ActionBar actionBar;
	private static final String[] DUMMY_CREDENTIALS = new String[] {
			"foo@example.com:hello", "bar@example.com:world" };
	private CustomDialog alertDialog;
	private CustomDialog aboutDialog;

	/**
	 * The default email to populate the email field with.
	 */
	public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";
	private static final String TAG="LoginActivity";

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private UserLoginTask mAuthTask = null;

	// Values for email and password at the time of the login attempt.
	private String mEmail;
	private String mPassword;

	// UI references.
	private EditText mEmailView;
	private EditText mPasswordView;
	private View mLoginFormView;
	private View mLoginStatusView;
	private TextView mLoginStatusMessageView;
	private Intent i;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_login);
		intView();
		
	
	}

	
	public void intView() {
		actionBar = this.getActionBar();
		actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setDisplayShowHomeEnabled(true);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle(R.string.login);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		// Set up the login form.
		mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
		mEmailView = (EditText) findViewById(R.id.email);
		mEmailView.setText(mEmail);
		aboutDialoglayout = (RelativeLayout) LayoutInflater.from(
				LoginActivity.this).inflate(R.layout.about_dialog, null);
		
		aboutDialog = new CustomDialog(LoginActivity.this, aboutDialoglayout,
				R.style.Theme_dialog);
		aboutDialog.setCanceledOnTouchOutside(true);
		
		mPasswordView = (EditText) findViewById(R.id.password);
		mPasswordView
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView textView, int id,
							KeyEvent keyEvent) {
						if (id == R.id.login || id == EditorInfo.IME_NULL) {
							attemptLogin();
							return true;
						}
						return false;
					}
				});

		mLoginFormView = findViewById(R.id.login_form);
		mLoginStatusView = findViewById(R.id.login_status);
		mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

		findViewById(R.id.sign_in_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptLogin();
					}
				});
		
		
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.login_menu, menu);
		return true;
	}

	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home: 
			Intent i = new Intent(this, MainActivity.class);
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
			this.finish();
			return true;
		case R.id.regist:
			i = new Intent(LoginActivity.this, RegistActivity.class);
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
			break;
		case R.id.menu_about:
			//
			if (aboutDialog != null)
				aboutDialog.show();
			break;
		
		case R.id.menu_exit:
			//
			if (alertDialog != null)
				alertDialog.show();
			//
			break;

	
		}

		return super.onOptionsItemSelected(item);
	}
	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		if (mAuthTask != null) {
			return;
		}

		// Reset errors.
		mEmailView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		mEmail = mEmailView.getText().toString();
		mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} else if (mPassword.length() < 4) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(mEmail)) {
			mEmailView.setError(getString(R.string.error_field_required));
			focusView = mEmailView;
			cancel = true;
		} 
		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
			showProgress(true);
			mAuthTask = new UserLoginTask();
			mAuthTask.execute((Void) null);
		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mLoginStatusView.setVisibility(View.VISIBLE);
			mLoginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mLoginFormView.setVisibility(View.VISIBLE);
			mLoginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO: attempt authentication against a network service.
			HttpClient httpclient = new DefaultHttpClient();
			// 你的URL
			HttpPost httppost = new HttpPost("http://proxy.njut.asia/BookShare/mobile/member/login");
			String strResult = "";
			try {
				ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
						2);
				// Your DATA
				nameValuePairs.add(new BasicNameValuePair("username", mEmail));
				nameValuePairs.add(new BasicNameValuePair("password", mPassword));
				nameValuePairs.add(new BasicNameValuePair("mobile", "yes"));

				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf8"));
				HttpResponse response = httpclient.execute(httppost);
				/* 若状态码为200，Post成功 */
				if (response.getStatusLine().getStatusCode() == 200) {
					/* 读返回数据 */
					strResult = EntityUtils.toString(response.getEntity());
				} else {
					strResult = "Error Response:"+ response.getStatusLine().toString();
							
							
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			strResult = strResult.trim();
		

			Log.v(TAG, strResult);
			// TODO: 登陆用户的判断.
			try {
			    JSONTokener jsonParser = new JSONTokener(strResult);  

			    JSONObject loginInfo = (JSONObject) jsonParser.nextValue(); 
		
			    if(loginInfo.getInt("status")==0){ //用户名或者密码错误
			    	return false;
			    }else {
				    JSONTokener infoParser = new JSONTokener(loginInfo.getString("info"));  
				    JSONObject userInfo = (JSONObject) infoParser.nextValue(); 
				    Log.v(TAG, userInfo.getString("nickname"));		
				     String PREFS_NAME = "asia.njut.book";
					 SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);			
				    settings.edit().putString("nickname", userInfo.getString("nickname")).commit();  
				    settings.edit().putString("user_id", userInfo.getString("user_id")).commit();  
				    settings.edit().putString("username", userInfo.getString("username")).commit();  
				    settings.edit().putString("password", userInfo.getString("password")).commit();  
				    settings.edit().putString("email", userInfo.getString("email")).commit();
				    settings.edit().putString("mhash", userInfo.getString("mhash")).commit();
				    settings.edit().putString("IsLogined", "YES").commit();
				    
			    	return true;
				}
			    

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			

		
			
			
			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mAuthTask = null;
			showProgress(false);

			if (success) {
					 
				Toast.makeText(getApplicationContext(), "登陆成功",
					     Toast.LENGTH_SHORT).show();
				
				Intent intent = new Intent(LoginActivity.this, MainActivity.class);
	                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	                LoginActivity.this.startActivity(intent);  
	                LoginActivity.this.overridePendingTransition(R.anim.activity_enter, R.anim.activity_exit);
	                LoginActivity.this.finish();   
	               
			} else {
				mPasswordView
						.setError(getString(R.string.error_incorrect_usernameorpassword));
				mPasswordView.requestFocus();
			}
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;
			showProgress(false);
		}
	}
}
